
package com.htd.htdapmservice.task;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.htd.htdapmapi.alarm.request.AlarmInto;
import com.htd.htdapmapi.alarm.result.AlarmResult;
import com.htd.htdapmcommon.constants.ErrorCodeConstants;
import com.htd.htdapmcommon.enums.AlarmSendStatus;
import com.htd.htdapmcommon.enums.AlarmsLevelEnum;
import com.htd.htdapmcommon.enums.AlarmsStatusEnum;
import com.htd.htdapmdmo.DataCompare;
import com.htd.htdapmdmo.LogAnalyzeErrorRecord;
import com.htd.htdapmservice.dao.DataCompareDao;
import com.htd.htdapmservice.service.intf.OneAlertService;
import com.taobao.pamirs.schedule.IScheduleTaskDealMulti;
import com.taobao.pamirs.schedule.TaskItemDefine;

/**
 * task
 * @since 2018.10.29
 * 功能描述：在表“data_compare”表中获取数据，作为参数调用创建告警API功能，调用成功后，将表“data_compare”中
 * 		  “status”字段的值由“SEND_NO”改为“SEND_YES”
 */
@Component("dataCompareAlarmTask")
public class DataCompareAlarmTask implements IScheduleTaskDealMulti<DataCompare> {
    private static final Logger logger = LoggerFactory.getLogger(DataCompareAlarmTask.class);

    @Autowired
    private DataCompareDao dataCompareDao;

    @Autowired
    private OneAlertService  oneAlertService;

    /**
     *
     * @param dataCompareList
     * @param ownSign
     * @return
     * @throws Exception
     */
    @Override
    public boolean execute(DataCompare[] dataCompareList, String ownSign) throws Exception {
        logger.info("dataCompareAlarmTask execute Entrance, itemBrands : {}, ownSign : {}", JSONObject.toJSONString(dataCompareList), JSONObject.toJSONString(ownSign));
        boolean result = true;
        try {
            if (dataCompareList!=null &&dataCompareList.length>0) {
                for (DataCompare dataCompare : dataCompareList) {
                	AlarmInto alarmInto=new AlarmInto();
                	BeanCopier copier = BeanCopier.create(DataCompare.class, AlarmInto.class, false);
            		copier.copy(dataCompare,alarmInto, null);
                	alarmInto.setEventType(AlarmsStatusEnum.ALARM_TRIGGER.getCode());
                	alarmInto.setPriority(AlarmsLevelEnum.LEVEL_TWO.getCode());
                	alarmInto.setProductType(dataCompare.getProductTypeCode());
                    AlarmResult alarmResult = oneAlertService.createAlarm(alarmInto);
                    //创建告警成功时，更新dataCompare表中status的状态为“SEND_YES”
					if (ErrorCodeConstants.SUCCESS_CODE.equals(alarmResult.getResponseCode())) {
						Map<String, Object> paramMap = new HashMap<>();
						paramMap.put("id", dataCompare.getId());
						paramMap.put("status", AlarmSendStatus.SEND_YES.getCode());
						dataCompareDao.updateAlarmStatus(paramMap);
					}
                }
            }
        }catch (Exception e) {
            logger.error("dataCompareAlarmTask execute error", e);
            result = false;
        }
        return result;
    }
    
   
    /**
     * 选择任务数据。
     * @param taskParameter 任务参数
     * @param ownSign 当前环境名称
     * @param taskQueueNum 当前任务类型的任务队列数量
     * @param taskItemList 当前调度服务器，分配到的可处理队列
     * @param eachFetchDataNum 每次获取数据的数量
     * @return
     * @throws Exception
     */

    @Override
    public List<DataCompare> selectTasks(String taskParameter, String ownSign, int taskQueueNum, List<TaskItemDefine> taskItemList, int eachFetchDataNum) throws Exception {
        logger.info("dataCompareAlarmTask selectTasks Entrance, taskParameter : {}, ownSign : {}, taskQueueNum : {}, taskItemList : {}," +
                "eachFetchDataNum : {}", new Object[]{JSONObject.toJSONString(ownSign), JSONObject.toJSONString(taskParameter),
                JSONObject.toJSONString(taskQueueNum), JSONObject.toJSONString(taskItemList), JSONObject.toJSONString(eachFetchDataNum)});
        List<DataCompare> dataCompareList = new ArrayList<DataCompare>();
        try{
            List<String> taskIdList = new ArrayList<String>();
            Map<String, Object> paramMap = new HashMap<>();
            if (taskItemList != null && taskItemList.size() > 0) {
                for (TaskItemDefine taskItem : taskItemList) {
                    taskIdList.add(taskItem.getTaskItemId());
                }
                // 根据id和队列数取摩，在taskIdList中则被该任务查询并执行
                paramMap.put("taskQueueNum", taskQueueNum);
                paramMap.put("taskIdList", taskIdList);
                // 默认查询数量
                paramMap.put("rows", eachFetchDataNum > 0 ? eachFetchDataNum : 20);
                dataCompareList = dataCompareDao.findDataCompareListByStatus(AlarmSendStatus.SEND_NO.getCode());
            }
        } catch (Exception e){
            logger.error("dataCompareAlarmTask selectTasks error:", e);
        }
        return dataCompareList;
    }

    @Override
    public Comparator getComparator() {
        return new Comparator<LogAnalyzeErrorRecord>() {
            public int compare(LogAnalyzeErrorRecord o1, LogAnalyzeErrorRecord o2) {
                Long id1 = o1.getId();
                Long id2 = o2.getId();
                return id1.compareTo(id2);
            }
        };
    }

	

}


